<template>
  <div>
    <div class="">
      <mt-field
        label="用户"
        v-model="regForm.name"
        type="text"
        placeholder="请输入用户"
      />

      <mt-field
        label="密码"
        v-model="regForm.password"
        type="password"
        placeholder="请输入密码"
      />

      <mt-field
        label="确认"
        v-model="regForm.password2"
        type="password"        
        placeholder="请确认密码"
      />

      <mt-field
        label="邮箱"
        v-model="regForm.email"
        type="email"
        placeholder="请输入邮箱"
      />

      <div class="content-padded">
        <mt-button @click="onClickRegister" size="large">注册</mt-button>
      </div>
      <div class="content-padded">
        <p>注册成功后的用户可用于登录</p>
      </div>
    </div>
  </div>
</template>

<script>
import {Register} from "@/api/user.js"
export default {
  data() {
    return {
      regForm: {
        name: "",
        password: "",
        password2: "",
        email: "",
      },
    };
  },
  methods: {
    async onClickRegister() {      
      if (this.regForm.name === "") {
        this.$toast("用户不能为空");
        return;
      } else if (this.regForm.password === "") {
        this.$toast("密码不能为空");
        return;
      } else if (this.regForm.password != this.regForm.password2) {
        this.$toast("密码两次输入不一致");
        return;
      } else if (this.regForm.email === "") {
        this.$toast("邮箱不能为空");
        return;
      }

      try {
        let user = this.regForm;
        delete user.password2;  //删除该临时的字段
        let result = await Register(user);
        if (result.code === 1) {
          this.$store.commit("user/setUser", result.data.user); //保存用户信息，还是处于未登录
          this.$router.push({ name: "login" })
        }

      } catch (error) {
        this.$messagebox("注册失败",error);
      }   
    },
  },
};
</script>

<style lang="scss" scoped>
.mui-input-group {
  margin-top: 10px;
  background-color: transparent;
}
.mui-input-group label {
  width: 22%;
}
.mui-input-row:last-child {
  background: #fff;
}
.mui-input-row {
  margin-top: 20px;
  background: #fff;
}
.mui-input-row label ~ input,
.mui-input-row label ~ select,
.mui-input-row label ~ textarea {
  width: 78%;
}
.link-area {
  display: block;
  margin-top: 25px;
  text-align: center;
}
.content-padded {
  margin-top: 30px;
}
</style>

